package com.kaf.common.exception;

import com.kaf.common.domain.CommonResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * 全局异常处理器
 * 集中处理项目中所有异常，提供统一的错误响应格式
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理所有未知异常
     * @param e 异常
     * @param request 请求
     * @return 统一错误响应
     */
    @ExceptionHandler(Exception.class)
    public CommonResult<String> handleException(Exception e, HttpServletRequest request) {
        log.error("全局异常处理，请求路径: {}，异常信息: {}", request.getRequestURI(), e.getMessage(), e);
        return CommonResult.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统繁忙，请稍后再试");
    }

    /**
     * 处理业务异常
     * @param e 业务异常
     * @param request 请求
     * @return 统一错误响应
     */
    @ExceptionHandler(BusinessException.class)
    public CommonResult<String> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.error("业务异常，请求路径: {}，异常信息: {}", request.getRequestURI(), e.getMessage(), e);
        return CommonResult.fail(e.getCode(), e.getMessage());
    }

    /**
     * 处理参数校验异常
     * @param e 参数校验异常
     * @param request 请求
     * @return 统一错误响应
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        log.error("参数校验异常，请求路径: {}，异常信息: {}", request.getRequestURI(), e.getMessage());

        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();

        StringBuilder errorMessage = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            errorMessage.append(fieldError.getDefaultMessage()).append(";");
        }

        return CommonResult.fail(HttpStatus.BAD_REQUEST.value(), errorMessage.toString());
    }

    /**
     * 处理空指针异常
     * @param e 空指针异常
     * @param request 请求
     * @return 统一错误响应
     */
    @ExceptionHandler(NullPointerException.class)
    public CommonResult<String> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        log.error("空指针异常，请求路径: {}，异常信息: {}", request.getRequestURI(), e.getMessage(), e);
        return CommonResult.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "系统内部错误");
    }
}
